import html2Canvas from 'html2canvas';

/**
 * html转图片
 * @param obj
 * @param width
 * @param height
 * @returns {Promise<unknown>}
 */
export const html2CanvasUtils = (obj, width, height) => {
    return new Promise((resolve, reject) => {
        html2Canvas(obj, {
            width: width, // 宽度，单位为像素
            height: height, // 高度，单位为像素
            useCORS: false, // 是否允许跨域请求
            allowTaint: true, // 是否允许污染画布
            logging: false, // 是否启用日志记录
            scale: 1 // 画布的缩放级别
        }).then(function(canvas) {
            const data = canvas.toDataURL('image/jpeg', 1.0);
            if (data) {
                resolve(data);
            }
        });
    });
};
/**
 * html转图片
 * @param html
 * @returns {Promise<unknown>}
 */
export const htmlToImageBase64 = (html) => {
    return new Promise(async(resolve, reject) => {
        // 创建一个div将要转换的html放进去
        let div = document.createElement('div');
        // 设置div的id
        div.id = 'dome_div';
        div.innerHTML = html;
        document.body.appendChild(div);
        let editorObj = div.getElementsByClassName('editor-content')[0];
        if (editorObj === undefined) {
            // 删除创建的div
            document.body.removeChild(div);
            reject(new Error('未找到可转换的html'));
        }
        let width = editorObj.offsetWidth;
        let height = editorObj.offsetHeight;
        await html2CanvasUtils(editorObj, width, height).then((canvas) => {
            // 删除创建的div
            document.body.removeChild(div);
            resolve(canvas);
        });
    });
};
